import {
  getInspectStandardByPage,
  addInspectStandard,
  updateInspectStandard,
  delInspectStandard,
  exportInspectStandard,
  getTemplateIdlist,
} from '@/services/device/inspectStandard';
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Col, Form, Input, message, Modal, Row, Tooltip, Tree } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import moment from 'moment';
import { tableSearchPublicConfig } from '@/utils/filterUtils';

import { Item } from 'rc-menu';
const InspectStandard: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(true); //编辑框的disable
  const [templateIdListInfo, setTemplateIdListInfo] = useState<any[]>([]); //模板编号下拉框
  const [templateId, setTemplateId] = useState(); //父组件传递的大模板id
  const [form] = Form.useForm();
  const ref = useRef(null);
  /* hook钩子，加载DOM获取父组件传入的参数 */
  useEffect(() => {
    console.log('父组件传入的参数：', props);
    if (props.templateId) {
      actionRef.current?.reload();
      setTemplateId(props.templateId);
    }
  }, [props.templateId]);
  /* 巡检计划有效标记颜色tag组件 */
  const IsValidAndIsAttachedColorTag = ({ isBlue, text }) => {
    const tagStyle = {
      textalign: 'center',

      width: '50px',
      height: '27px',
      padding: '5px',
      borderRadius: '3px',
      color: 'white',
      fontSize: '10px',
      backgroundColor: '#13c2c2',
    };
    if (isBlue) {
      tagStyle.backgroundColor = '#13c2c2';
    } else {
      tagStyle.backgroundColor = '#DC6C76';
    }
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={tagStyle}>{text}</div>
      </div>
    );
  };
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      align: 'center',
      sorter: true,
      width: 80,
    },
    {
      title: '模板编号',
      dataIndex: 'templateId',
      align: 'center',
      sorter: true,

      width: 150,
      search: false,
    },
    {
      title: '检查项目',
      dataIndex: 'checkItem',
      align: 'center',
      sorter: true,

      width: 200,
    },
    // {
    //   title: '唯一标识',
    //   dataIndex: 'identification',
    // },
    // {
    //   title: '顺序编号',
    //   dataIndex: 'sequence',
    // },
    {
      title: '检查描述',
      align: 'center',
      sorter: true,

      dataIndex: 'checkDesc',
      width: 300,
      search: false,
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
      onCell: () => {
        return {
          style: {
            maxWidth: 300,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
    },
    {
      title: '是否需要附件',
      dataIndex: 'isAttached',
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
      align: 'center',
      sorter: true,

      render: (text: boolean) => (
        <IsValidAndIsAttachedColorTag isBlue={text} text={text ? '是' : '否'} />
      ),
      width: 100,
    },
    {
      title: '是否有效',
      align: 'center',
      sorter: true,

      dataIndex: 'isValid',
      valueType: 'select',
      fieldProps: {
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
      render: (text: boolean) => (
        <IsValidAndIsAttachedColorTag isBlue={text} text={text ? '有效' : '无效'} />
      ),
      width: 90,
    },

    {
      title: '备注',
      align: 'center',
      sorter: true,

      search: false,
      hideInTable: true,
      dataIndex: 'notes',
      width: 300,
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
      onCell: () => {
        return {
          style: {
            maxWidth: 300,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
            cursor: 'pointer',
          },
        };
      },
    },
    // {
    //   title: '顺序编号',
    //   dataIndex: 'sequence',
    // },

    {
      title: '创建日期', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      dataIndex: 'createTime',
      width: 120,
      render: (text, record) => <div>{moment(text).format('YYYY-MM-DD')}</div>,
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      align: 'center',
      sorter: true,

      dataIndex: 'createName',
      width: 120,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      align: 'center',

      fixed: 'right',
      width: 100,
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              checkDesc: record.checkDesc,
              checkItem: record.checkItem,
              identification: record.identification,
              isAttached: record.isAttached ? 'true' : 'false', //需要将Boolean类型转换为String类型，不然ProformSelect获取不到form的值
              isValid: record.isValid ? 'true' : 'false', //需要将Boolean类型转换为String类型，不然ProformSelect获取不到form的值
              notes: record.notes,
              sequence: record.sequence,
              templateId: record.templateId,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delInspectStandard({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      console.log(values);
      values.templateId = templateId;
      const result = await addInspectStandard(values);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateInspectStandard(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="巡检计划模板查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={tableSearchPublicConfig}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              const filters = filterTran(ref.current.getFieldsValue());
              exportInspectStandard({
                current: 1,
                pageSize: 5000,
                filters: filters,
              }).then((res) => {
                const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                aLink.setAttribute('download', `InspectStandard.xlsx`);
                aLink.click();
                document.body.removeChild(aLink);
              });
            }}
            type="primary"
          >
            导出
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          console.log('过滤参数：', params);
          params.CheckItem = params.checkItem;
          const res = { ...params, templateId: templateId };
          const sorters = sortTran(sort);
          const filters = filterTran(res);
          console.log('filter参数：', res);
          const result = await getInspectStandardByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          /* 巡检模板数据 创建日期字段 只保留年月日 */
          result.data.content.map((item: any) => {
            item.createTime = item.createTime.split(' ')[0];
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 2000, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={handleSubmit}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        initialValues={{
          identification: '巡检模板',
          templateId: templateId,
        }}
      >
        <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
        <ProFormText
          name="identification"
          label="唯一标识"
          initialValue={11}
          // disabled={true}
          hidden={true}
        />
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="checkItem"
              label="检查项目"
              placeholder="请输入检查项目"
              rules={[{ required: true, message: '请输入检查项目!' }]}
              // disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="templateId"
              label="模板编号"
              rules={[{ required: true, message: '请选择模版编号!' }]}
              options={templateIdListInfo}
              disabled={true}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              name="isAttached"
              label="是否需要附件"
              rules={[{ required: true, message: '请选择是否需要附件!' }]}
              valueEnum={{
                true: '是',
                false: '否',
              }}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="isValid"
              label="是否有效"
              rules={[{ required: true, message: '请选择是否有效!' }]}
              valueEnum={{
                true: '是',
                false: '否',
              }}
            />
          </Col>
        </Row>
        <ProFormTextArea
          name="checkDesc"
          label="检查描述"
          rules={[{ required: true, message: '请输入检查描述!' }]}
          placeholder="请输入检查描述"
          fieldProps={{ width: '100%', showCount: true, maxLength: 100, rows: 3 }}
          // disabled={createOrUpdate}
        />
        <ProFormText
          name="notes"
          label="备注"
          hidden={true}
          // disabled={createOrUpdate}
        />
        {/* <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormText
              name="checkItem"
              label="检查项目"
              placeholder="请输入检查项目"
              rules={[{ required: true, message: '请输入 your checkItem!' }]}
              // disabled={createOrUpdate}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="templateId"
              label="模板编号"
              rules={[{ required: true, message: '请输入 your templateId!' }]}
              valueEnum={templateIdListInfo}
              // disabled={createOrUpdate}
            />
          </Col>
        </Row>
        <Row gutter={[50, 0]}>
          <Col span={12}>
            <ProFormSelect
              name="isAttached"
              label="是否需要附件"
              options={[
                {
                  value: 'true',
                  label: '是',
                },
                {
                  value: 'false',
                  label: '否',
                },
              ]}
              rules={[{ required: true, message: '请输入!' }]}
            />
          </Col>
          <Col span={12}>
            <ProFormSelect
              name="isValid"
              label="是否有效"
              options={[
                {
                  value: 'true',
                  label: '是',
                },
                {
                  value: 'false',
                  label: '否',
                },
              ]}
              rules={[{ required: true, message: '请输入 your isValid!' }]}
            />
          </Col>
        </Row>
        <ProFormText
          name="checkDesc"
          label="检查描述"
          placeholder="请输入检查描述"
          rules={[{ required: true, message: '请输入 your checkDesc!' }]}
          // disabled={createOrUpdate}
        />
        <ProFormTextArea
          name="notes"
          label="备注"
          colProps={{ span: 24 }}
          rules={[{ required: true, message: '请输入 your notes!' }]}
          // disabled={createOrUpdate}
        />
        <ProFormText
          name="sequence"
          label="顺序编号"
          rules={[{ required: true, message: '请输入 your sequence!' }]}
          // disabled={createOrUpdate}
        /> */}
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default InspectStandard;
